package com.yx.common.core.tree;

import cn.hutool.core.util.ObjectUtil;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class TreeUtils {


    /**
     * 结构树
     * @param list 菜单数据
     * @param rootId 根节点
     * @param pid_name 父节点属性名称
     * @param primary_name 主键名称
     * @param child_name 子级
     * @param sort 排序字段
     * @param <T>
     * @param <E>
     * @param <S>
     * @return
     * @throws Exception
     * @throws IllegalAccessException
     */
    public static <T, E, S> List<T> buildTree(List<T> list, E rootId,String pid_name,String primary_name, String child_name, S sort) throws  Exception, IllegalAccessException {
        List<T> TList =  new ArrayList<>();
        if(ObjectUtil.isNotEmpty(list)) {
            for (int i = 0 ; i< list.size(); i++){
                T t = list.get(i);
                Class<?> aClass = t.getClass();
                Field id = getSuperFiled(aClass, primary_name);
                //Field id = aClass.getDeclaredField(PRIMARY_KEY);
                id.setAccessible(true);
                Integer currentId = (Integer) id.get(t);
                Field parentId = getSuperFiled(aClass, pid_name);
                parentId.setAccessible(true);
                //注意：当前默认是转int 这块后期改成泛型获取类型的方式。sort 同样
                Integer parentId1 = (Integer) parentId.get(t);
                if (parentId1 == rootId) {
                    Field roleList1 = getSuperFiled(aClass, child_name);
                    roleList1.setAccessible(true);
                    roleList1.set(t, buildTree(list,currentId,pid_name,primary_name,child_name,sort));
                    TList.add(t);
                    if(ObjectUtil.isNotNull(sort)){
                        Field sortField = getSuperFiled(aClass, sort);
                        sortField.setAccessible(true);
                        TList = TList.stream().sorted(Comparator.comparing(c -> {
                            try {
                                return (Integer) sortField.get(c);
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            return null;
                        })).collect(Collectors.toList());
                    }
                }
            }
        }
        return TList;
    }

    public static  <E> Field getSuperFiled(Class clazz, E filedName) throws Exception {

        Field data = null;
        try {
            data = clazz.getDeclaredField(filedName.toString());
        } catch (NoSuchFieldException e) {
            data = clazz.getSuperclass().getDeclaredField(filedName.toString());
        }
        return  data;
    }

}
